<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { showImagePreview } from 'vant'
import defaultAvatar from '@/assets/images/default-avatar.svg'
import serviceAvatar from '@/assets/images/logo.svg'

interface Message {
  id: number
  type: 'text' | 'image'
  content: string
  sender: 'me' | 'service'
  timestamp: number
  avatar: string
}

const messages = ref<Message[]>([])
const newMessage = ref('')
const chatHistoryRef = ref<HTMLElement | null>(null)
const imageInputRef = ref<HTMLInputElement | null>(null)

/**
 * Scrolls the chat history to the bottom.
 */
async function scrollToBottom() {
  await nextTick()
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  }
}

/**
 * Placeholder for saving a message to the backend.
 * @param {Message} message - The message to save.
 */
async function saveMessageToApi(message: Message) {
  // TODO: Implement API call to save the message
  console.log('Saving message to backend:', message)
  return Promise.resolve()
}

/**
 * Simulates a reply from the customer service.
 */
function simulateServiceReply(sentMessage: Message) {
  setTimeout(() => {
    const isReplyingToImage = sentMessage.type === 'image'
    const replyText = isReplyingToImage ? '图片收到啦！' : '您好，您刚才说的是：' + `"${sentMessage.content}"` + ' 吗？'

    const reply: Message = {
      id: Date.now(),
      type: 'text',
      content: replyText,
      sender: 'service',
      timestamp: Date.now(),
      avatar: serviceAvatar,
    }
    messages.value.push(reply)
    scrollToBottom()
  }, 1200)
}

/**
 * Sends a new message from the user.
 */
async function sendMessage() {
  const text = newMessage.value.trim()
  if (!text) return

  const message: Message = {
    id: Date.now(),
    type: 'text',
    content: text,
    sender: 'me',
    timestamp: Date.now(),
    avatar: defaultAvatar,
  }

  messages.value.push(message)
  newMessage.value = ''
  
  await scrollToBottom()

  // Save to backend (placeholder)
  await saveMessageToApi(message)

  // Simulate a reply
  simulateServiceReply(message)
}

/**
 * Checks if a timestamp should be displayed for a message.
 * A timestamp is shown if it's the first message or if more than 5 minutes have passed since the previous one.
 * @param {number} index - The index of the message in the array.
 */
function shouldShowTimestamp(index: number): boolean {
  if (index === 0) return true
  const currentTimestamp = messages.value[index].timestamp
  const previousTimestamp = messages.value[index - 1].timestamp
  return (currentTimestamp - previousTimestamp) > 5 * 60 * 1000 // 5 minutes
}

/**
 * Formats a timestamp into a user-friendly string (e.g., "昨天 17:04").
 * @param {number} timestamp - The timestamp to format.
 */
function formatTimestamp(timestamp: number): string {
  const date = new Date(timestamp)
  const now = new Date()
  const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)

  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const timeStr = `${hours}:${minutes}`

  if (date.toDateString() === now.toDateString()) {
    return timeStr
  }
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${timeStr}`
  }
  const weekMap = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  if (now.getTime() - date.getTime() < 7 * 24 * 60 * 60 * 1000) {
    return `${weekMap[date.getDay()]} ${timeStr}`
  }
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${timeStr}`
}

function triggerImageUpload() {
  imageInputRef.value?.click()
}

function handleImageUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = async (e) => {
    const imageUrl = e.target?.result as string
    const message: Message = {
      id: Date.now(),
      type: 'image',
      content: imageUrl,
      sender: 'me',
      timestamp: Date.now(),
      avatar: defaultAvatar,
    }
    messages.value.push(message)
    
    await scrollToBottom()
    await saveMessageToApi(message)
    simulateServiceReply(message)
  }
  reader.readAsDataURL(file)

  // Reset input value to allow selecting the same file again
  if (target) target.value = ''
}

function previewImage(url: string) {
  showImagePreview([url])
}

onMounted(() => {
  // Add an initial greeting message from the service
  messages.value.push({
    id: Date.now(),
    type: 'text',
    content: '您好！我是您的专属客服，很高兴为您服务。',
    sender: 'service',
    timestamp: Date.now() - 6 * 60 * 1000, // 6 minutes ago to show timestamp
    avatar: serviceAvatar,
  })
})
</script>

<template>
  <div class="chat-container">
    <!-- Header -->
    <!-- <div class="chat-header">
      客服
    </div> -->

    <!-- Chat History -->
    <div ref="chatHistoryRef" class="chat-history">
      <div v-for="(message, index) in messages" :key="message.id" class="message-group">
        <!-- Timestamp -->
        <div v-if="shouldShowTimestamp(index)" class="timestamp">
          {{ formatTimestamp(message.timestamp) }}
        </div>
        <!-- Message -->
        <div :class="['message-item', message.sender]">
          <img :src="message.avatar" class="avatar" />
          <div class="message-content">
            <div v-if="message.type === 'text'" class="message-bubble">
              {{ message.content }}
            </div>
            <div v-else-if="message.type === 'image'" class="image-bubble" @click="() => previewImage(message.content)">
              <img :src="message.content" class="message-image" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Chat Input Area -->
    <div class="chat-input-area">
      <van-icon name="photo-o" size="24" @click="triggerImageUpload" class="input-icon" />
      <input
        ref="imageInputRef"
        type="file"
        accept="image/*"
        class="hidden-file-input"
        @change="handleImageUpload"
      />
      <van-field
        v-model="newMessage"
        placeholder="请输入..."
        class="chat-input"
        @keyup.enter="sendMessage"
      />
      <van-button type="primary" class="send-button" @click="sendMessage">
        发送
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  @apply flex flex-col h-screen bg-gray-100 dark:bg-[#121212];
}

.chat-header {
  @apply flex-shrink-0 text-center py-3 font-semibold bg-gray-200 dark:bg-[#1e1e1e] text-black dark:text-white;
  border-bottom: 1px solid var(--van-border-color);
}

.chat-history {
  @apply flex-1 overflow-y-auto p-4;
}

.message-group {
  @apply mb-4;
}

.timestamp {
  @apply text-center text-sm text-gray-400 dark:text-gray-500 my-4;
  font-size: 10px;
  margin-bottom: 8px;
}

.message-item {
  @apply flex items-start gap-3 my-4;
}

.message-item.me {
  @apply flex-row-reverse;
}

.avatar {
  /* @apply w-11 h-11 rounded-md flex-shrink-0; */
  border-radius: var(--radius-md);
  flex-shrink: 0;
  width: calc(var(--spacing) * 34);
}

.message-content {
  @apply relative;
}

.message-bubble {
  /* @apply py-2 px-3 rounded-md text-base leading-snug; */
  min-height: 44px; /* Align with avatar height */
  display: flex;
  align-items: center;
  font-size: 12px;
}

.message-item.service .message-bubble {
  @apply bg-white dark:bg-[#262626] text-black dark:text-white;
  padding: 5px;
}

.message-item.me .message-bubble {
  @apply bg-[#a9e979] dark:bg-[#528442] text-black dark:text-white;
  padding: 5px;
}

/* Bubble tails */
.message-bubble::before {
  /* content: '';
  position: absolute;
  top: 14px;
  width: 0;
  height: 0;
  border-style: solid;
  color: red; */
}
.message-item.service .message-bubble::before {
  left: -8px;
  border-width: 6px 8px 6px 0;
  border-color: transparent var(--bubble-bg) transparent transparent;
  border-width: 10px 15px 10px 0; /* 向左 */
  border-color: transparent rgb(34, 27, 130) transparent transparent; /* 仅右边框显色 */
}
.message-item.me .message-bubble::before {
  right: -8px;
  border-width: 6px 0 6px 8px;
  border-color: transparent transparent transparent var(--bubble-bg-me);
  border-width: 10px 15px 10px 0; /* 向右 */
  border-color: transparent red transparent transparent; /* 仅右边框显色 */
}
.light .message-item.service .message-bubble::before { --bubble-bg: #fff; }
.dark .message-item.service .message-bubble::before { --bubble-bg: #262626; }
.light .message-item.me .message-bubble::before { --bubble-bg-me: #a9e979; }
.dark .message-item.me .message-bubble::before { --bubble-bg-me: #528442; }

/* Image Bubble */
.image-bubble {
  @apply rounded-md overflow-hidden cursor-pointer;
  max-width: 50vw;
}
.message-image {
  @apply block max-w-full h-auto;
}

/* Input Area */
.chat-input-area {
  @apply flex-shrink-0 flex items-center p-2 bg-gray-200 dark:bg-[#1e1e1e] border-t border-gray-300 dark:border-gray-700;
}
.input-icon {
  @apply mx-2 text-gray-600 dark:text-gray-400 cursor-pointer;
}
.hidden-file-input {
  @apply hidden;
}
.chat-input {
  @apply flex-1;
  --van-field-padding-left: 0.75rem;
  --van-field-padding-right: 0.75rem;
  --van-cell-background: theme('colors.white');
  border-radius: 0.375rem;
}
.dark .chat-input {
  --van-cell-background: theme('colors.gray.700');
  --van-field-input-text-color: theme('colors.white');
  --van-field-placeholder-text-color: theme('colors.gray.400');
}
.send-button {
  @apply ml-2;
}
</style>

<route lang="json5">
{
  name: 'service',
  meta: {
    title: '客服',
    i18n: 'layouts.service'
  }
}
</route> 